home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / util / gnu / unixcmds.lha / unixcmds / src / head.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-06  |  1.6 KB  |  80 lines

  1. /* head - print the first few lines of a file   Author: Andy Tanenbaum */
  2.  
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. #define DEFAULT 10
  7.  
  8. int main  (int argc, char **argv);
  9. void do_file  (int n, FILE *f);
  10. void usage  (void);
  11.  
  12. int main(argc, argv)
  13. /* [<][>][^][v][top][bottom][index][help] */
  14. int argc;
  15. char *argv[];
  16. {
  17.   FILE *f;
  18.   int n, k, nfiles;
  19.   char *ptr;
  20.  
  21.   /* Check for flag.  Only flag is -n, to say how many lines to print. */
  22.   k = 1;
  23.   ptr = argv[1];
  24.   n = DEFAULT;
  25.   if (argc > 1 && *ptr++ == '-') {
  26.         k++;
  27.         n = atoi(ptr);
  28.         if (n <= 0) usage();
  29.   }
  30.   nfiles = argc - k;
  31.  
  32.   if (nfiles == 0) {
  33.         /* Print standard input only. */
  34.         do_file(n, stdin);
  35.         exit(0);
  36.   }
  37.  
  38.   /* One or more files have been listed explicitly. */
  39.   while (k < argc) {
  40.         if (nfiles > 1) printf("==> %s <==\n", argv[k]);
  41.         if ((f = fopen(argv[k], "r")) == NULL)
  42.                 printf("head: cannot open %s\n", argv[k]);
  43.         else {
  44.                 do_file(n, f);
  45.                 fclose(f);
  46.         }
  47.         k++;
  48.         if (k < argc) printf("\n");
  49.   }
  50.   return(0);
  51. }
  52.  
  53.  
  54.  
  55. void do_file(n, f)
  56. /* [<][>][^][v][top][bottom][index][help] */
  57. int n;
  58. FILE *f;
  59. {
  60.   int c;
  61.  
  62.   /* Print the first 'n' lines of a file. */
  63.   while (n) switch (c = getc(f)) {
  64.             case EOF:
  65.                 return;
  66.             case '\n':
  67.                 --n;
  68.             default:    putc((char) c, stdout);
  69.         }
  70. }
  71.  
  72.  
  73. void usage()
  74. /* [<][>][^][v][top][bottom][index][help] */
  75. {
  76.   fprintf(stderr, "Usage: head [-n] [file ...]\n");
  77.   exit(1);
  78. }
  79. /* [<][>][^][v][top][bottom][index][help] */
  80.